import { home } from './protobuf-loader'
import { getHttp, http } from './http';
import { getToken } from '@/utils/auth';

export const getHomeData = async () => {
  const request = new home.HomeDataRequest(); 
  if (getToken() === "")
      request.setLogin(false)
  else {
    request.setLogin(true);
    request.setToken(getToken())
  }
  const response = await getHttp().post('/home/data',request.serializeBinary())
  const ret = home.HomeDataResponse.deserializeBinary(response.data);
  return {
    featuredProblems: ret.getFeaturedProblemsList().map(p => {
      const obj = p.toObject();
      return {
        ...obj,
        problemId: obj.id,
        problemTitle: obj.title,
        difficultyLevel: obj.difficulty
      };
    }),
    featuredArticles: ret.getFeaturedArticlesList().map(a => a.toObject())
  }
}

// 搜索内容
export const searchContent = async (params) => {
  try {
    const request = new home.SearchRequest();
    request.setToken(params.token || '');
    request.setQuery(params.query);
    request.setType(params.type);
    request.setPage(params.page || 1);
    request.setPageSize(params.page_size || 20);
    
    const response = await getHttp().post('/home/search', request.serializeBinary());
    
    if (response.data) {
      const result = home.SearchResponse.deserializeBinary(response.data);
      
      return {
        success: result.getSuccess(),
        message: result.getMessage(),
        problems: result.getProblemsList().map(p => {
          const obj = p.toObject();
          return {
            ...obj,
            problemId: obj.id,
            problemTitle: obj.title,
            difficultyLevel: obj.difficulty
          };
        }),
        blogs: result.getBlogsList().map(b => b.toObject()),
        users: result.getUsersList().map(u => {
          const obj = u.toObject();
          return {
            ...obj,
            username: obj.name,  // 映射name字段到username
            id: obj.email        // 使用email作为id
          };
        }),
        total: result.getTotal()
      };
    }
    
    throw new Error('搜索响应数据为空');
  } catch (error) {
    console.error('搜索请求失败:', error);
    throw error;
  }
}
